﻿<template>
  <div style="padding: 20px; background: #f5f5f5; min-height: 100vh;">
    <!-- 页面标题 -->
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
      <h2 style="margin: 0; color: #333;">商品采购统计</h2>
    </div>

    <!-- 搜索栏 -->
    <div style="background: #fff; padding: 20px; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
      <div style="display: flex; gap: 15px; align-items: center; flex-wrap: wrap;">
        <div style="display: flex; align-items: center; gap: 8px;">
          <label style="color: #666; font-size: 14px;">商品名称</label>
          <input 
            v-model="query.productName" 
            @keyup.enter="search" 
            placeholder="商品名称" 
            style="padding: 8px 12px; border: 1px solid #dcdfe6; border-radius: 6px; width: 200px;"
          />
        </div>
        <div style="display: flex; align-items: center; gap: 8px;">
          <label style="color: #666; font-size: 14px;">规格型号</label>
          <input 
            v-model="query.specification" 
            @keyup.enter="search" 
            placeholder="规格型号" 
            style="padding: 8px 12px; border: 1px solid #dcdfe6; border-radius: 6px; width: 200px;"
          />
        </div>
        <div style="display: flex; align-items: center; gap: 8px;">
          <label style="color: #666; font-size: 14px;">采购日期</label>
          <input 
            v-model="query.purchaseDate" 
            type="date" 
            style="padding: 8px 12px; border: 1px solid #dcdfe6; border-radius: 6px; width: 150px;"
          />
        </div>
        <button @click="search" style="padding: 8px 16px; border: 1px solid #3b82f6; border-radius: 6px; background: #3b82f6; color: #fff; cursor: pointer;">
          查询
        </button>
        <button @click="reset" style="padding: 8px 16px; border: 1px solid #dcdfe6; border-radius: 6px; background: #fff; color: #666; cursor: pointer;">
          重置
        </button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 20px;">
      <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; border-radius: 8px; color: #fff; text-align: center;">
        <div style="font-size: 24px; font-weight: bold; margin-bottom: 8px;">{{ statistics.totalCount || 0 }}</div>
        <div style="font-size: 14px; opacity: 0.9;">总采购数量</div>
      </div>
      <div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); padding: 20px; border-radius: 8px; color: #fff; text-align: center;">
        <div style="font-size: 24px; font-weight: bold; margin-bottom: 8px;">{{ (statistics.totalAmount || 0).toFixed(2) }}</div>
        <div style="font-size: 14px; opacity: 0.9;">总采购金额</div>
      </div>
      <div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); padding: 20px; border-radius: 8px; color: #fff; text-align: center;">
        <div style="font-size: 24px; font-weight: bold; margin-bottom: 8px;">{{ statistics.productCount || 0 }}</div>
        <div style="font-size: 14px; opacity: 0.9;">商品种类</div>
      </div>
      <div style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); padding: 20px; border-radius: 8px; color: #fff; text-align: center;">
        <div style="font-size: 24px; font-weight: bold; margin-bottom: 8px;">{{ statistics.supplierCount || 0 }}</div>
        <div style="font-size: 14px; opacity: 0.9;">供应商数量</div>
      </div>
    </div>

    <!-- 商品采购列表 -->
    <div style="background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
      <div style="padding: 20px; border-bottom: 1px solid #ebeef5;">
        <h3 style="margin: 0; color: #333; font-size: 16px;">所有商品采购统计信息</h3>
      </div>

      <div v-if="loading" style="padding: 40px; text-align: center; color: #666;">
        加载中...
      </div>

      <div v-else-if="list.length === 0" style="padding: 40px; text-align: center; color: #666;">
        暂无数据
      </div>

      <div v-else style="overflow-x: auto;">
        <table style="width: 100%; border-collapse: collapse;">
          <thead>
            <tr style="background: #f8f9fa;">
              <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ebeef5; color: #666;">商品名称</th>
              <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ebeef5; color: #666;">规格型号</th>
              <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ebeef5; color: #666;">单位</th>
              <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ebeef5; color: #666;">总数量</th>
              <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ebeef5; color: #666;">平均单价</th>
              <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ebeef5; color: #666;">总金额</th>
              <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ebeef5; color: #666;">采购次数</th>
              <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ebeef5; color: #666;">最后采购日期</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in list" :key="item.id" style="border-bottom: 1px solid #f0f0f0;">
              <td style="padding: 12px; color: #333;">{{ item.productName || '-' }}</td>
              <td style="padding: 12px; color: #333;">{{ item.specification || '-' }}</td>
              <td style="padding: 12px; color: #333;">{{ item.unit || '-' }}</td>
              <td style="padding: 12px; color: #333;">{{ item.totalQuantity || 0 }}</td>
              <td style="padding: 12px; color: #333;">{{ item.avgUnitPrice?.toFixed(2) || '0.00' }}</td>
              <td style="padding: 12px; color: #333;">{{ item.totalAmount?.toFixed(2) || '0.00' }}</td>
              <td style="padding: 12px; color: #333;">{{ item.purchaseCount || 0 }}</td>
              <td style="padding: 12px; color: #333;">{{ formatDate(item.lastPurchaseDate) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 分页 -->
    <div style="display: flex; justify-content: center; align-items: center; margin-top: 20px; gap: 10px;">
      <button @click="prevPage" :disabled="pageNum === 1" style="padding: 8px 12px; border: 1px solid #dcdfe6; border-radius: 6px; background: #fff; cursor: pointer; color: #666;">
        上一页
      </button>
      <span style="color: #666; font-size: 14px;">
        第 {{ pageNum }} 页，共 {{ Math.ceil(total / pageSize) }} 页，总计 {{ total }} 条
      </span>
      <button @click="nextPage" :disabled="pageNum * pageSize >= total" style="padding: 8px 12px; border: 1px solid #dcdfe6; border-radius: 6px; background: #fff; cursor: pointer; color: #666;">
        下一页
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { apiGet } from '../../utils/api.js'

// 响应式数据
const loading = ref(false)
const list = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)

// 统计概览数据
const statistics = ref({
  totalCount: 0,
  totalAmount: 0,
  productCount: 0,
  supplierCount: 0
})

// 搜索条件
const query = reactive({
  productName: '',
  specification: '',
  purchaseDate: ''
})

// 生命周期
onMounted(() => {
  load()
  loadOverview()
})

// 方法
async function load() {
  loading.value = true
  try {
    const params = {
      current: pageNum.value,
      size: pageSize.value,
      ...query
    }

    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const qs = new URLSearchParams(params).toString()
    const response = await apiGet(`/procure-service/purchase-statistics/page${qs ? `?${qs}` : ''}`)

    // 处理API响应数据结构
    if (response && response.data) {
      list.value = response.data.records || []
      total.value = response.data.total || 0
    } else if (response && response.records) {
      list.value = response.records || []
      total.value = response.total || 0
    } else {
      list.value = []
      total.value = 0
    }

    console.log('采购统计数据:', response)
    
    // 数据加载完成后，如果概览统计为空，则从列表数据计算
    if (statistics.value.totalCount === 0 && list.value.length > 0) {
      calculateStatisticsFromList()
    }
  } catch (error) {
    console.error('加载失败:', error)
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

async function loadOverview() {
  try {
    const params = { ...query }

    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const qs = new URLSearchParams(params).toString()
    const response = await apiGet(`/procure-service/purchase-statistics/overview${qs ? `?${qs}` : ''}`)

    console.log('统计概览API响应:', response)

    // 处理API响应数据结构
    if (response && response.data) {
      statistics.value = {
        totalCount: response.data.totalCount || 0,
        totalAmount: response.data.totalAmount || 0,
        productCount: response.data.productCount || 0,
        supplierCount: response.data.supplierCount || 0
      }
    } else if (response) {
      statistics.value = {
        totalCount: response.totalCount || 0,
        totalAmount: response.totalAmount || 0,
        productCount: response.productCount || 0,
        supplierCount: response.supplierCount || 0
      }
    } else {
      // 如果概览API失败，从列表数据计算统计信息
      calculateStatisticsFromList()
    }

    console.log('处理后的统计概览数据:', statistics.value)
  } catch (error) {
    console.error('加载统计概览失败:', error)
    // 如果概览API失败，从列表数据计算统计信息
    calculateStatisticsFromList()
  }
}

// 从列表数据计算统计信息
function calculateStatisticsFromList() {
  if (list.value && list.value.length > 0) {
    const totalCount = list.value.reduce((sum, item) => sum + (item.totalQuantity || 0), 0)
    const totalAmount = list.value.reduce((sum, item) => sum + (item.totalAmount || 0), 0)
    const productCount = list.value.length
    const supplierCount = new Set(list.value.map(item => item.supplierId || item.supplierName).filter(Boolean)).size
    
    statistics.value = {
      totalCount,
      totalAmount,
      productCount,
      supplierCount
    }
    
    console.log('从列表数据计算的统计信息:', statistics.value)
  } else {
    statistics.value = {
      totalCount: 0,
      totalAmount: 0,
      productCount: 0,
      supplierCount: 0
    }
  }
}

function search() {
  pageNum.value = 1
  load()
  loadOverview()
}

function reset() {
  query.productName = ''
  query.specification = ''
  query.purchaseDate = ''
  pageNum.value = 1
  load()
  loadOverview()
}

function prevPage() {
  if (pageNum.value > 1) {
    pageNum.value--
    load()
  }
}

function nextPage() {
  if (pageNum.value * pageSize.value < total.value) {
    pageNum.value++
    load()
  }
}

function formatDate(dateString) {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>
